const fs = require("fs");
const FormData = require("form-data");
const { axios, getToken } = require("./weix");

function upload(url, filePath) {
  let formData = new FormData();
  formData.append("media", fs.createReadStream(filePath));

  var headers = formData.getHeaders(); //获取headers
  return new Promise((resolve, reject) => {
    //获取form-data长度
    formData.getLength(async function (err, length) {
      if (err) {
        return;
      }
      //设置长度，important!!!
      headers["content-length"] = length;
      axios
        .post(url, formData, { headers })
        .then((res) => {
          if (res.status === 200) {
            resolve(res.data);
          } else {
            reject(`upload(): error code ${res.status}`);
          }
        })
        .catch(function (err) {
          reject(`upload(): ${err.message}`);
        });
    });
  });
}

exports.uploadTemporaryMedia = async function (type, file) {
  return upload(
    "cgi-bin/media/upload?access_token=" + (await getToken()) + "&type=" + type,
    file
  );
};

exports.addLimitMaterial = async function () {
  return axios
    .post("cgi-bin/media/uploadnews?access_token=" + (await getToken()), {
      articles: [
        {
          thumb_media_id:
            "sL-w-mPmhOYBPw-vgxgzQbfoOm-_2L385EIevAb0by2uqdQxyPW2amVEA6evO4sh",
          author: "xxx",
          title: "Happy Day",
          content_source_url: "frp.familybaby.top",
          content: `<h1>test</h1><div>真的</div>`,
          digest: "digest",
          show_cover_pic: 1,
          need_open_comment: 1,
          only_fans_can_comment: 1,
        },
      ],
    })
    .then((res) => res.data);
};

exports.upload = upload;
